package com.apestech.api.condition.conlib;

import com.apestech.api.tables.TableExec;
import com.apestech.formwork.condition.ExecDimension;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.xml.condition.modul.Condition;
import com.apestech.framework.xml.plugin.modul.SpecialField;
import com.apestech.framework.xml.table.modul.Tables;

public class ConExec extends ConPub {

    public ConExec(Condition condition) throws Exception {
        super(condition);
    }

    public void execTable() throws Exception {
        execTable(null, null, "exec", null);
    }

    public void execTableByM(String id, String mid, String personId) throws Exception {
        String tabName=super.getCondition().getTableKey().getTabName(mid);
        execTable(tabName, id, "exec", personId);
    }

    public void execTable(String tabName, Object id, String state, String personId) throws Exception {
        for(int i=0; i<super.getTableSize(); i++){
            Tables tab=super.getTables().get(i);
            if(tabName==null || tab.getMasterTable().equals(tabName)){
                JSONArray qlist=null;
                if(id==null){
                    SpecialField.Field sysField=super.getSession().getSpecialField();
                    qlist=super.getSession().getForJSON().query("SELECT "+tab.getMasterKey()+" FROM "+tab.getMasterTableId()+" WHERE "+sysField.getApproveDate()+" IS NULL ");
                    int qlen=qlist.size();
                    for(int q=0; q<qlen; q++){
                        exeTable(qlist.get(q).get(tab.getMasterKey()), tab, state, personId);
                    }
                } else exeTable(id, tab, state, personId);
                if(tabName!=null) break;
            }
        }
    }

    private void exeTable(Object id, Tables tab, String state, String personId) throws Exception {
        TableExec table=new TableExec(super.getSession(), tab);
        table.execTable(id, new ExecDimension(tab, state, personId));
    }

    public void stopTableByM(String id, String mid, String personId) throws Exception {
        String tabName=super.getCondition().getTableKey().getTabName(mid);
        execTable(tabName, id, "stop", personId);
    }

}
